/*
 * FileDescriptorTable.cpp
 *
 *  Created on: Jul 11, 2009
 *      Author: elkobir
 */

#include "FileDescriptorTable.h"

FileDescriptorTable::FileDescriptorTable() {
	for (int i = 0; i < 12; i++){
		int emptyVal = -9; //  EMPTY_INDEX is -9 compiler broblems ?!?;
		_fdTable.push_back(emptyVal);
	}

}

FileDescriptorTable::FileDescriptorTable(FileDescriptorTable& ofd){
	for (int i = 0; i < 12; i++){
		_fdTable.push_back(ofd._fdTable.at(i));
	}

}

FileDescriptorTable::~FileDescriptorTable() {
	// TODO Auto-generated destructor stub
}

int FileDescriptorTable::addFileDescriptor(int fd){
	int index = findIndexOfFileDescriptor(fd);
	if (index != -1){
		ostringstream str;
		str << "FileDescriptorTable::addFileDescriptor - cannot add fd="<< fd;
		str << " to table because it's already there at index= " <<  index << endl;
		Log::log(str,0,"error");
		return -1;
	}

	int emptyIndex = findIndexOfFirstEmptySpace();
	if (emptyIndex == -1){
		ostringstream str;
		str << "FileDescriptorTable::addFileDescriptor - cannot add fd="<< fd;
		str << " to table because the table is full." << endl;
		Log::log(str,0,"error");
		return -1;
	}

	_fdTable[emptyIndex] = fd;

	return 0;

}

int FileDescriptorTable::removeFileDescriptor(int fd){
	int index = findIndexOfFileDescriptor(fd);
	if (index == -1){
		ostringstream str;
		str << "FileDescriptorTable::removeFileDescriptor - cannot remove fd="<< fd;
		str << " to table because it's not there" << endl;
		Log::log(str,0,"error");
		return -1;
	}

	_fdTable[index] = EMPTY_INDEX;
	return 0;
}

int FileDescriptorTable::findIndexOfFileDescriptor(int fd){
	for (unsigned int i = 0; i < _fdTable.size(); i++){
		if (_fdTable.at(i) == fd){
			return i;
		}
	}
	return -1;
}

int FileDescriptorTable::findIndexOfFirstEmptySpace(){
	int emptyIndexValue = EMPTY_INDEX;
	for (unsigned int i = 0; i < _fdTable.size(); i++){
		if (_fdTable.at(i) == emptyIndexValue){
			return i;
		}
	}
	return -1;
}

int FileDescriptorTable::getFileDescriptorByIndex(int index){
	if (index < 0 || index >= 12){
		ostringstream str;
		str << "FileDescriptorTable::FileDescriptorTable - invalid index ="<< index;
		Log::log(str,0,"error");
		return -1;
	}
	int res = _fdTable.at(index);
	return res;
}

bool FileDescriptorTable::isFull(){
	int ans = findIndexOfFirstEmptySpace();
	if (ans == -1)
		return true;
	return false;
}
